/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csci6450.chickenFriedFS.metaServer.threads;

import csci6450.chickenFriedFS.metaServer.MetaServerLog;
import csci6450.chickenFriedFS.metaServer.NuggetServerInfoLog;
import csci6450.chickenFriedFS.nuggetCore.Nugget;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

/**
 *
 * @author jacobschoen
 */
public class ForceReplicationManager extends Thread {

    private String serverIp;

    public ForceReplicationManager(String serverIp) {
        this.serverIp = serverIp;
    }

    @Override
    public void run() {
        List<Nugget> replicate = MetaServerLog.getInstance().serverDown(serverIp);

        for (int i = 0; i < replicate.size(); i = i + 1) {
            Replicate r = new Replicate(replicate.get(i));
            r.start();
        }

    }

    class Replicate extends Thread {

        private Nugget nugget;

        public Replicate(Nugget nugget) {
            this.nugget = nugget;
        }

        @Override
        public void run() {
            Socket socket = null;
            try {
                // open a socket connection

                socket = new Socket(nugget.getNuggetLocation(), NuggetServerInfoLog.getInstance().getNuggetServerInfo(nugget.getNuggetLocation()).getMetaPort());
                // open I/O streams for objects
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
                outputStream.writeObject(this.nugget);
                outputStream.flush();
            } catch (UnknownHostException ex) {
            } catch (IOException ex) {
            } catch (Exception ex) {
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }
}
